package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.AttentionGroupDetail;
import com.jp.knowledge.activity.AttentionListDetailInfo;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.SearchAttentionActivity;
import com.jp.knowledge.adapter.attention.AttentionGroupAdapter;
import com.jp.knowledge.adapter.attention.AttentionListAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.AttentionData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.attention.CompanyListModel;
import com.jp.knowledge.my.activity.OrganizeActivity;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.view.SwipeItemLayout;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 528787067@qq.com on 2017/3/17.
 */

public class FragmentAttention extends BaseFragment implements View.OnClickListener, ResultSubscriber.OnResultListener, CanRefreshLayout.OnRefreshListener {

    private static final long AUTO_REFRESH_TIME = 10 * 60 * 1000;

    private static final int GET_ATTENTION_GROUP_CODE = 0x01;
    private static final int GET_ATTENTION_LIST_CODE = 0x02;
    private static final int LIST_ITEM_DELETE_CODE = 0x03;
    private static final int GROUP_DETAIL_CODE = 0x04;
    private static final int STICK_TOP = 0x05;

    private Context context;
    private View contentView;
    private LinearLayout watchMoreLly;
    private TextView watchMoreBtn;
    private ImageView watchMoreIv;
    private CanRefreshLayout refreshLayout;
    private RecyclerView groupRv;
    private LinearLayout attentionListNoneView;
    private ImageView attentionEmptyToAdd;
    private RecyclerView attentionListRv;

    private List<CompanyListModel.ListBean> companyModels;
    private AttentionGroupAdapter attentionGroupAdapter;
    private List<AttentionData> attentionDatas;
    private AttentionListAdapter attentionListAdapter;

    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    private Handler timerRefreshHandler;
    private Runnable timerRefreshRunnable;

    private FileCacheManager cacheManager;
    private String groupCachePath;
    private String attentionListCachePath;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.context = getContext();
        this.contentView = View.inflate(context, R.layout.fragment_attention, null);
        this.watchMoreLly = (LinearLayout) contentView.findViewById(R.id.attention_more_lly);
        this.watchMoreBtn = (TextView) contentView.findViewById(R.id.attention_more_tv);
        this.watchMoreIv = (ImageView) contentView.findViewById(R.id.attention_more_iv);
        this.refreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
        this.groupRv = (RecyclerView) contentView.findViewById(R.id.attention_group_rv);
        this.attentionListRv = (RecyclerView) contentView.findViewById(R.id.attention_list_rv);
        this.attentionListNoneView = (LinearLayout) contentView.findViewById(R.id.attentionNoListView);
        this.attentionEmptyToAdd = (ImageView) contentView.findViewById(R.id.attention_list_empty_to_add);
        this.watchMoreLly.setTag(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View topBar = contentView.findViewById(R.id.top_bar);
            int statusBarHeight = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0)
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            topBar.setPadding(0, statusBarHeight, 0, 0);
        }

        init();
        return contentView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == GROUP_DETAIL_CODE && resultCode == RESULT_OK && data != null){
            if(!data.getBooleanExtra("hasNew", true)) {
                try {
                    companyModels.get(data.getIntExtra("position", -1)).setUpdate(0);
                } catch (Exception e){} finally {
                    updateAttentinoGroupAdapter(companyModels);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        saveCacheToLocal(companyModels, groupCachePath);
        saveCacheToLocal(attentionDatas, attentionListCachePath);
        super.onDestroy();
    }

    private void init(){
        companyModels = new ArrayList<>();
        attentionDatas = new ArrayList<>();

        ((TextView)contentView.findViewById(R.id.module_name)).setText("雷达");
        ImageView searchIcon = (ImageView) contentView.findViewById(R.id.icon_serach);
        searchIcon.setImageResource(R.mipmap.guanzhutianjia);
        searchIcon.setOnClickListener(this);
        watchMoreLly.setOnClickListener(this);
        refreshLayout.setRefreshEnabled(true);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.setOnRefreshListener(this);
        attentionEmptyToAdd.setOnClickListener(this);

        groupRv.setHasFixedSize(true);
        groupRv.addItemDecoration(new JpDiver(context));
        groupRv.setLayoutManager(new LinearLayoutManager(context){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        attentionGroupAdapter = new AttentionGroupAdapter(context, companyModels);
        groupRv.setAdapter(attentionGroupAdapter);
        attentionGroupAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if("organizeGroup".equals(companyModels.get(position).getId())){
                    startActivity(new Intent(mContext, OrganizeActivity.class));
                } else if(companyModels.get(position).getAuditState() != 1
                        && !"myGroup".equals(companyModels.get(position).getId())){

                } else {
                    startActivityForResult(new Intent(context, AttentionGroupDetail.class)
                                    .putExtra("companyModel", companyModels.get(position))
                                    .putExtra("position", position),
                            GROUP_DETAIL_CODE);
                }
            }
        });

        attentionListRv.setHasFixedSize(true);
        attentionListRv.addItemDecoration(new JpDiver(context));
        attentionListRv.setLayoutManager(new LinearLayoutManager(context){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        attentionListAdapter = new AttentionListAdapter(context, attentionDatas, true);
        attentionListRv.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(context));
        attentionListRv.setAdapter(attentionListAdapter);
        attentionListAdapter.setOnItemCallback(new AttentionListAdapter.OnItemCallback() {
            @Override
            public void onItemClick(int position) {
                startActivity(new Intent(mContext, AttentionListDetailInfo.class)
                        .putExtra("id", attentionDatas.get(position).getId())
                        .putExtra("title", attentionDatas.get(position).getTitle())
                        .putExtra("type", attentionDatas.get(position).getType()));
                attentionDatas.get(position).setNewNum(0);
                attentionListAdapter.notifyItemChanged(position);
            }
            @Override
            public void onStickTopClick(int position, boolean isTop) {
                AttentionData attentionData = attentionDatas.get(position);
                JsonObject param = new JsonObject();
                param.addProperty("id", attentionData.getId());
                param.addProperty("type", attentionData.getType());
                param.addProperty("op", isTop?1:0);
                HttpHelper.getInstance(mContext).attentionStickTop(param, position*10+STICK_TOP, FragmentAttention.this);

                attentionData.setIsTop(isTop?1:0);
                if(attentionData.getIsTop() == 1) {
                    attentionDatas.add(0, attentionDatas.remove(position));
                } else{
                    for(int i = 0; i < attentionDatas.size(); i++){
                        if(i != position && attentionDatas.get(i).getIsTop() != 1) {
                            attentionDatas.add(position<i?i-1:i, attentionDatas.remove(position));
                            break;
                        }
                    }
                }
                setAttentionListView(attentionDatas);
            }
            @Override
            public void onDeleteClick(int position) {
                JsonObject param = new JsonObject();
                param.addProperty("token", HttpHelper.token);
                param.addProperty("id",attentionDatas.get(position).getId());
                param.addProperty("type", attentionDatas.get(position).getType());
                HttpHelper.getInstance(context).subscribeOperate(param, position*10+LIST_ITEM_DELETE_CODE, FragmentAttention.this);
                attentionDatas.remove(position);
                setAttentionListView(attentionDatas);
            }
        });

        companyModels = insertDefaultGroup(companyModels, 0);
        updateAttentinoGroupAdapter(companyModels);
        initBroadCast();
        initTimer();
        initCache();
//        refreshLayout.autoRefresh();
        readGroupCache();
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(context);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(LocalBroadCast.GET_LOGIN_INFO.equals(action)){
                    refreshLayout.autoRefresh();
                } else if(LocalBroadCast.LOGOUT_SUCCESS_BROD.equals(action)){
                    companyModels.clear();
                    attentionDatas.clear();
                    companyModels = insertDefaultGroup(companyModels, 0);
                    updateAttentinoGroupAdapter(companyModels);
                    setAttentionListView(attentionDatas);
                } else if(LocalBroadCast.ADD_ATTENTION.equals(action)){
                    if(intent.getStringExtra("groupId") != null)
                        return;
                    AttentionData attentionData = (AttentionData) intent.getSerializableExtra("attentionData");
                    if(attentionData == null)
                        return;
                    if(intent.getBooleanExtra("isAttention", false)){
                        if(attentionData.getIsTop() == 1 || attentionDatas.size() == 0) {
                            attentionDatas.add(0, attentionData);
                        } else{
                            for(int i = 0; i < attentionDatas.size(); i++){
                                if(attentionDatas.get(i).getIsTop() != 1) {
                                    attentionDatas.add(i, attentionData);
                                    break;
                                }
                            }
                        }
                        setAttentionListView(attentionDatas);
                    } else{
                        for(int i = 0; i < attentionDatas.size(); i++){
                            if(!attentionDatas.get(i).getId().equals(attentionData.getId()))
                                continue;
                            attentionListAdapter.removeData(i);
                            break;
                        }
                    }
                } else if(LocalBroadCast.COMPANY_JOIN.equals(action)){
//                    OrganizaModel organizaModel = (OrganizaModel) intent.getSerializableExtra("joinCompany");
//                    if(organizaModel == null)
//                        return;
//                    if(organizaModel.getCompanyState() == 1     // 没有通过审核的公司
//                            && (organizaModel.getAuditStete() == 0 || organizaModel.getAuditStete() == 2))
//                        return;
//                    CompanyListModel.ListBean bean = new CompanyListModel.ListBean();
//                    bean.setUpdate(0);
//                    bean.setTitle(organizaModel.getCompanyName());
//                    bean.setId(organizaModel.getCompanyId());
//                    for(int i = 0; i < companyModels.size(); i++){
//                        if(!"myGroup".equals(companyModels.get(0).getId())) {
//                            companyModels.add(i, bean);
//                            break;
//                        }
//                    }
//                    updateAttentinoGroupAdapter(companyModels);
                    getGroupData();
                } else if(LocalBroadCast.COMPANY_EXIT.equals(action)){
//                    for(CompanyListModel.ListBean bean : companyModels){
//                        if(bean.getId().equals(intent.getStringExtra("companyId"))){
//                            companyModels.remove(bean);
//                            updateAttentinoGroupAdapter(companyModels);
//                            return;
//                        }
//                    }
                    getGroupData();
                }
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
        intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        intentFilter.addAction(LocalBroadCast.ADD_ATTENTION);
        intentFilter.addAction(LocalBroadCast.COMPANY_JOIN);
        intentFilter.addAction(LocalBroadCast.COMPANY_EXIT);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    private void initTimer(){
        timerRefreshHandler = new Handler();
        timerRefreshRunnable = new Runnable() {
            @Override
            public void run() {
                timerRefreshHandler.removeCallbacks(timerRefreshRunnable);
                getGroupData();
                attentionList();
                timerRefreshHandler.postDelayed(timerRefreshRunnable, AUTO_REFRESH_TIME);
            }
        };
    }

    private void initCache(){
        cacheManager = new FileCacheManager();
        groupCachePath = mContext.getCacheDir()+"/attention_group_" + HttpHelper.uuid + ".dat";
        attentionListCachePath = mContext.getCacheDir()+"/attention_list_" + HttpHelper.uuid + ".dat";
    }

    private List<CompanyListModel.ListBean> insertDefaultGroup(List<CompanyListModel.ListBean> listBeen, int defaultUpdate){
        CompanyListModel.ListBean bean = new CompanyListModel.ListBean();
        bean.setId("myGroup");
        bean.setTitle("我的分组");
        bean.setUpdate(defaultUpdate);
        bean.setAuditState(1);
        if(listBeen == null)
            listBeen = new ArrayList<>();
        if(listBeen.size() == 0){
            CompanyListModel.ListBean organizeBean = new CompanyListModel.ListBean();
            organizeBean.setId("organizeGroup");
            organizeBean.setTitle("组织分组");
            organizeBean.setUpdate(0);
            organizeBean.setAuditState(1);
            listBeen.add(organizeBean);
        }
        for(CompanyListModel.ListBean listBean : listBeen){
            if("myGroup".equals(listBean.getId())){
                listBeen.remove(listBean);
                break;
            }
        }
        listBeen.add(0, bean);
        return listBeen;
    }

    /* 获取组数据 */
    private void getGroupData(){
        HttpHelper.getInstance(context).attentionGroup(new JsonObject(), GET_ATTENTION_GROUP_CODE, this);
    }

    /* 获取关注列表数据 */
    private void attentionList(){
        HttpHelper.getInstance(context).attentionList(new JsonObject(), GET_ATTENTION_LIST_CODE, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.attention_list_empty_to_add:
            case R.id.icon_serach:
                startActivity(new Intent(mContext, SearchAttentionActivity.class));
                break;
            case R.id.attention_more_lly:
                watchMoreLly.setTag(!(boolean) watchMoreLly.getTag());
                updateAttentinoGroupAdapter(companyModels);
                break;
        }
    }

    private void updateAttentinoGroupAdapter(List<CompanyListModel.ListBean> companyModels){
        boolean isExpandList = (boolean) watchMoreLly.getTag();
        if(companyModels.size() > 3)
            watchMoreLly.setVisibility(View.VISIBLE);
        else
            watchMoreLly.setVisibility(View.GONE);
        if(isExpandList) {
            watchMoreBtn.setText("收起更多");
            watchMoreIv.setImageResource(R.mipmap.attention_drop_up);
        } else {
            watchMoreBtn.setText("展开更多");
            watchMoreIv.setImageResource(R.mipmap.attention_drop_down);
        }
        if((isExpandList && companyModels.size() > 3) || companyModels.size() <= 3)
            attentionGroupAdapter.updateAdapter(companyModels);
        else
            attentionGroupAdapter.updateAdapter(companyModels.subList(0, 3));
    }

    private void setAttentionListView(List<AttentionData> attentionDatas){
        if(attentionDatas != null && attentionDatas.size() > 0) {
            attentionListNoneView.setVisibility(View.GONE);
            attentionListRv.setVisibility(View.VISIBLE);
            attentionListAdapter.updateAdapter(attentionDatas);
        } else{
            attentionListRv.setVisibility(View.GONE);
            attentionListNoneView.setVisibility(View.VISIBLE);
        }
    }

    /* 读取分组缓存 */
    private void readGroupCache(){
        Observable.create(new Observable.OnSubscribe<List<CompanyListModel.ListBean>>() {
            @Override
            public void call(Subscriber<? super List<CompanyListModel.ListBean>> subscriber) {
                List<CompanyListModel.ListBean> groupData = (List<CompanyListModel.ListBean>) cacheManager.readObject(groupCachePath);
                subscriber.onNext(groupData);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<CompanyListModel.ListBean>>() {
            @Override
            public void onCompleted() {
                readAttentionListCache();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<CompanyListModel.ListBean> data) {
                companyModels.clear();
                if(data != null && data.size() > 0)
                    companyModels.addAll(data);
                companyModels = insertDefaultGroup(companyModels, 0);
                updateAttentinoGroupAdapter(companyModels);
                onCompleted();
            }
        });
    }

    /* 读取关注列表缓存 */
    private void readAttentionListCache(){
        Observable.create(new Observable.OnSubscribe<List<AttentionData>>() {
            @Override
            public void call(Subscriber<? super List<AttentionData>> subscriber) {
                List<AttentionData> listData = (List<AttentionData>) cacheManager.readObject(attentionListCachePath);
                subscriber.onNext(listData);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<AttentionData>>() {
            @Override
            public void onCompleted() {
                refreshLayout.autoRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<AttentionData> data) {
                attentionDatas.clear();
                if(data != null && data.size() > 0)
                    attentionDatas.addAll(data);
                setAttentionListView(attentionDatas);
                onCompleted();
            }
        });
    }

    private void saveCacheToLocal(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }

    @Override
    public void onRefresh() {
        timerRefreshHandler.removeCallbacks(timerRefreshRunnable);
        getGroupData();
        attentionList();
        timerRefreshHandler.postDelayed(timerRefreshRunnable, AUTO_REFRESH_TIME);
    }

    private boolean groupDataGetting;
    private boolean attentionListDataGetting;
    @Override
    public void onStart(int requestType) {
        if(requestType == GET_ATTENTION_GROUP_CODE)
            groupDataGetting = true;
        else if(requestType == GET_ATTENTION_LIST_CODE)
            attentionListDataGetting = true;
    }
    @Override
    public void onCompleted(int requestType) {
        if(requestType == GET_ATTENTION_GROUP_CODE)
            groupDataGetting = false;
        else if(requestType == GET_ATTENTION_LIST_CODE)
            attentionListDataGetting = false;
        if(!groupDataGetting && !attentionListDataGetting) {
            refreshLayout.refreshComplete();
            refreshLayout.loadMoreComplete();
        }
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
        } else if(requestType == GET_ATTENTION_GROUP_CODE){
            companyModels.clear();
            CompanyListModel companyListModel = data.getEntity(CompanyListModel.class);
            if(companyListModel.getList() != null && companyListModel.getList().size() > 0)
                companyModels.addAll(companyListModel.getList());
            companyModels = insertDefaultGroup(companyModels, companyListModel.getDefaultUpdate());
            updateAttentinoGroupAdapter(companyModels);
        } else if(requestType == GET_ATTENTION_LIST_CODE){
            attentionDatas.clear();
            List<AttentionData> attentionList = data.getList(AttentionData.class);
            if(attentionList != null && attentionList.size() > 0)
                attentionDatas.addAll(attentionList);
            setAttentionListView(attentionDatas);
        } else if(requestType%10 == STICK_TOP){
        } else if(requestType%10 == LIST_ITEM_DELETE_CODE){}
    }
}
